<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>RichTextEditor</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=0">
    <script src="./tinymce/tinymce.min.js"></script>
    <script src="./jquery-3.1.1.min.js"></script>
    <link rel="stylesheet" type="text/css" href="./style.css">
</head>

<body>
    <div id="title" style="outline: 0px solid transparent;" class="without-border field" placeholderText="Title" contenteditable="true"></div>
    <div contenteditable=false id=separatorDiv><hr></div>
    <div id="content" class="field" placeholderText="Content"></div>
    <p id="dummyP" style="display:none;"></p>
</body>

<script type="text/javascript">
    //resize editor area to fit window
    var dummyP = $('#dummyP');
    var hr = $('#hr');
    var body = $('body');
    var contentHeight = window.innerHeight
                        - parseInt(body.css('marginTop'))
                        - parseInt(body.css('marginBottom'))
                        - parseInt(dummyP.css('marginTop'))
                        - $('#title').outerHeight()
                        - hr.outerHeight()
                        - parseInt(hr.css('marginTop'))
                        - parseInt(hr.css('marginBottom'));
    $('#content').css('height', contentHeight + 'px');

    // lang
    var ms = location.href.match(/lang=(.+)/);
    var lang = 'en';
    if (ms) {
        lang = ms[1].toLowerCase();
    }
    if (lang.indexOf('zh') >= 0) {
        $('#title').attr('placeholderText', '标题')
        $('#content').attr('placeholderText', '内容')
    }

    var titleDiv = document.getElementById('title');
    function getTitle() {
        return titleDiv.innerText;
    }

    function setTitle(title) {
        return titleDiv.innerText = title;
    }

    tinymce.init({
        selector: 'div#content',
        remove_trailing_brs: false,
        element_format: 'html',
        allow_unsafe_link_target: true,
        plugins: 'lists',
        toolbar: false,
        menubar: false,
        inline: true,
    });

    function toggleBold() {
        tinyMCE.editors[0].formatter.toggle('bold');
        var currentState = tinyMCE.editors[0].formatter.match('bold');
        nativeCallbackHandler.onFormatChange(JSON.stringify({bold : currentState}));
    }

    function toggleBlockquote() {
        tinyMCE.editors[0].formatter.toggle('blockquote');
        var currentState = tinyMCE.editors[0].formatter.match('blockquote');
        nativeCallbackHandler.onFormatChange(JSON.stringify({blockquote:currentState}));
    }

    function toggleHeader() {
        var currentHeader = getCurrentHeader();
        if (currentHeader) {
            var currentVal = parseInt(currentHeader.substr(1));
            var newVal = (currentVal + 1) % 7;
            if (newVal) {
                tinyMCE.editors[0].formatter.apply('h' + newVal);
            } else {
                tinyMCE.editors[0].formatter.remove(currentHeader);
            }
        } else {
            tinyMCE.editors[0].formatter.apply('h1');
        }
        currentHeader = getCurrentHeader();
        nativeCallbackHandler.onFormatChange(JSON.stringify({header: currentHeader}));
    }

    function getCurrentHeader() {
        var intrestFormats = [
            'h1',
            'h2',
            'h3',
            'h4',
            'h5',
            'h6'
        ];
        var result = tinyMCE.editors[0].formatter.matchAll(intrestFormats);
        if (result) {
            return result[0];
        } else {
            return '';
        }
    }

    function getSelectedContent() {
        return $("#content").html();
        // 因为历史原因, mindMap的data-src="-", 如果这样, 就导致mindMap的src="-", 所以直接返回html
        return tinyMCE.editors[0].selection.getContent();
    }

    function toggleItalic() {
        tinyMCE.editors[0].formatter.toggle('italic');
        var currentState = tinyMCE.editors[0].formatter.match('italic');
        nativeCallbackHandler.onFormatChange(JSON.stringify({italic: currentState}));
    }

    function toggleBulletList() {
        tinyMCE.editors[0].execCommand('InsertUnorderedList', false)
        var listState = getListState();
        listState = listState.toLowerCase() === 'ul';
        nativeCallbackHandler.onFormatChange(JSON.stringify({bullet: listState}));
    }

    function toggleOrderedList() {
        tinyMCE.editors[0].execCommand('InsertOrderedList', false)
        var listState = getListState();
        listState = listState.toLowerCase() === 'ol';
        nativeCallbackHandler.onFormatChange(JSON.stringify({ordered: listState}));
    }

    function insertImage(src) {
        tinyMCE.editors[0].insertContent('<img src="' + src + '" alt=""/>');
    }

    function formatLink(url) {
        tinyMCE.editors[0].formatter.apply('link', {
            href: url
        });
        nativeCallbackHandler.onFormatChange(JSON.stringify({link: url}));
    }

    function removeLink(title, url) {
        tinyMCE.editors[0].formatter.remove('link');
        nativeCallbackHandler.onFormatChange(JSON.stringify({link: null}));
    }

    function enable() {
        document.addEventListener('selectionchange', selectionChangeHandler, false);
        document.removeEventListener('click', clickHandeler, false);
        tinyMCE.editors[0].setMode('design');
        titleDiv.setAttribute("contenteditable", true);
    }

    function disable() {
        document.removeEventListener('selectionchange', selectionChangeHandler, false);
        document.addEventListener('click', clickHandeler, false);
        tinyMCE.editors[0].setMode('readonly');
        titleDiv.setAttribute('contenteditable', false);
    }

    function clickHandeler(e) {
        var target = e.target;
        if (target.tagName === 'A') {
            var link = target.getAttribute('href');
            var title = target.innerHTML;
            e.preventDefault();
            nativeCallbackHandler.linkTo(link);
        } else if (target.tagName === 'IMG') {
            var src = target.getAttribute('src');
            e.preventDefault();
            nativeCallbackHandler.onClickedImage(src);
        }
    }

    function selectionChangeHandler() {
        var intrestFormats = ['bold',
            'italic',
            'h1',
            'h2',
            'h3',
            'h4',
            'h5',
            'h6',
            'blockquote',
            'link'
        ];
        var result = tinyMCE.editors[0].formatter.matchAll(intrestFormats);
        listState = getListState();
        if (listState) {
            result.push(listState);
        }
        var reg = RegExp('^h[1-6]$');
        var enabledFormat = {};
        result.reduce(function (previousValue, currentValue, index, array) {
            if (reg.test(currentValue)) {
              array[index] = 'header';
            }
            switch (array[index]) {
                case 'link':
                    enabledFormat[array[index]] = getLink();
                    break;
                default:
                    enabledFormat[array[index]] = true;
            }

        }, null);

        console.log(enabledFormat);
        nativeCallbackHandler.onCursorChanged(JSON.stringify(enabledFormat));
    }

    function getLink() {
        return tinyMCE.editors[0].selection.getNode().getAttribute('href');
    }

    function getContent() {
        var body = tinyMCE.$(tinyMCE.editors[0].getBody()).clone();
        return tinyMCE.$(body).clone().html();
    }

    function getListState() {
        var node = tinyMCE.editors[0].selection.getNode()
        var parents = tinymce.dom.DomQuery(node).parents();
        var lists = tinyMCE.util.Tools.grep(parents, isNodeList);
        if (lists.length > 0) {
            return lists[0].nodeName.toLowerCase();
        } else {
            return '';
        }
    }

    function isNodeList(node) {
        return node && (/^(OL|UL|DL)$/).test(node.nodeName) && isChildOfBody(node);
    }

    function isChildOfBody(elm) {
        return tinyMCE.editors[0].$.contains(tinyMCE.editors[0].getBody(), elm);
    }
</script>

</html>
